package common

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

const (
	SUCCESS_CODE      = 200
	DEFAULT_FAIL_CODE = 10000
)

// Success 成功信息+Data,如果没有参数data则传入nil
func Success(ctx *gin.Context, data any) {
	aid, _ := ctx.Get("aid")

	ctx.JSON(200, gin.H{
		"isOk": true,
		"aid":  aid,
		"msg":  "success",
		"data": data,
	})
}

// Fail 失败信息
func Fail(ctx *gin.Context, msg string, err error) {
	FailAndDetail(ctx, DEFAULT_FAIL_CODE, msg, err)
}

// FailAndDetail code+失败信息
func FailAndDetail(ctx *gin.Context, code int, msg string, err error) {
	if code <= SUCCESS_CODE { //code不能小于等于200
		code = DEFAULT_FAIL_CODE
	}

	aid, _ := ctx.Get("aid")

	var errStr string
	if err != nil {
		errStr = err.Error()
	}

	logrus.Infof("[aid: %s] <<< 接口响应客户端的失败数据:  code: %v, msg: %v, error: %v ❌️", aid, code, msg, errStr)

	//200是http请求成功，但是业务逻辑失败
	ctx.JSON(200, gin.H{
		"isOk":  false,
		"aid":   aid,    //请求ID
		"msg":   msg,    //消息提示
		"error": errStr, //错误信息
		"code":  code,   //自定义Code
	})
}
